/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.gmcc;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 
 * @author frank
 */
public class filter implements Filter {
	String nodeId = "";
	private static final boolean debug = false;

	// The filter configuration object we are associated with. If
	// this value is null, this filter instance is not currently
	// configured.
	private FilterConfig filterConfig = null;

	public filter() {
	}

	/**
	 * 
	 * @param request
	 *            The servlet request we are processing
	 * @param response
	 *            The servlet response we are creating
	 * @param chain
	 *            The filter chain we are processing
	 * 
	 * @exception IOException
	 *                if an input/output error occurs
	 * @exception ServletException
	 *                if a servlet error occurs
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		nodeId = request.getParameter("node");
		// System.out.println(nodeId);

		if (debug)
			log("TemplateFilter:doFilter()");
		// 桶状结构
		Throwable problem = null;
		// session.

		String webappName = (String) request.getAttribute("webappName");
		// System.err.println("webappName" + webappName + " "
		// + request.getAttributeNames());
		// request.getAttributeNames()
		String port = (String) request.getAttribute("port");
		try {
			Map model = new HashMap();
			// "unauthorized",新增一点功能。
			model.put("unauthorized", "OAAnnouncement");
			model.put("libUrl", "gmcc_ext");
			model.put("margins", "30 10 10 10");
			model.put("smcPrefix", "http://tp.cc.net/smc/mySmcPrefix");
			model.put("title", "test_title");
			model.put("layout", "TWT");
			model.put("name", "DEFAULT_HOMEPAGE");
			model.put("catalogId", "53c2f3ab-3795-4f44-a544-858fa3b9e2c0");
			if (null != nodeId && nodeId.equals("/全省共享资源")) {
				// System.out.println(nodeId);
				model.put("treeModelUrl", "http://localhost:" + 8080 + "/"
						+ "Phase2" + "/gmcc_ext/data/emulation/root.json");
				// "http://localhost:8080/Phase2/gmcc_ext/data/emulation/channel.json");
				// System.out.println(model.get("treeModelUrl"));
			} else {
				model.put("treeModelUrl",
				// "http://localhost:8080/Phase2/gmcc_ext/data/emulation/root.json"
						// "http://localhost:" + 8080 + "/" + "Phase2"
						// + "/" +
						"gmcc_ext/data/emulation/channel.json");
			}
			// model.put("margins", "35 35 35 35");

			Map channel = new HashMap();
			channel.put("maximizeUrl", "http://www.baidu.com"
			// "http://gmccnews.gmcc.net/portalnews.aspx?titlelength=100"
					);
			channel.put("editUrl", "http://www.google.cn"
			// "http://tpac-app.gmcc.net/smc/dummyChannel.html"
					);
			channel.put("serialNo", "1");
			channel.put("title", "天气预报");
			channel.put("height", 120);
			channel
					.put("contentUrl",
							"http://php.weather.sina.com.cn/search.php?city=%E5%B9%BF%E5%B7%9E&c=1&dpc=1");
			channel.put("layout", "T");
			channel.put("name", "GMCCInfoWeather_Channel");
			channel.put("catalogId", "2e9cf4db-ea29-4a48-9cfc-3e8edef966a3");
			channel.put("type", "1");
			Map channel1 = new HashMap();
			channel1.put("serialNo", "11");
			channel1.put("title", "要 闻");
			channel1.put("height", 160);
			channel1.put("contentUrl",
			// "http://news.qq.com/a/20091224/000405.htm"
					"http://aa.bb.cc.com");
			channel1.put("layout", "W");
			channel1.put("name", "NEWS_YW");
			channel1.put("catalogId", "caedaf72-b44a-46f2-9559-67fd8648611a");
			channel1.put("type", "0");
			Map channel2 = new HashMap();
			channel2.put("serialNo", "10");
			channel2.put("title", "OA公告");
			// channel2.put("height", 160);
			channel2.put("contentUrl", "http://www.ee.ff.gg.com"
			// "http://news.qq.com/a/20091224/000405.htm"

					);
			channel2.put("layout", "W");
			channel2.put("name", "OAAnnouncement");
			channel2.put("catalogId", "a7e0df5d-c6f8-455d-8af5-af2d609295ba");
			channel2.put("type", "0");
			Map channel3 = new HashMap();
			channel3.put("serialNo", 10);
			channel3.put("title", "股价");
			channel3.put("height", 160);
			// 对应的实际http位置：http://localhost:8080/Phase2/gmcc_ext/data/stock.html
			// 对应的物理文件路径：/home/gmcc/Workspaces/MyEclipse
			// 8.x/Phase2/WebRoot/gmcc_ext/data/stock.html
			channel3.put("contentUrl", "gmcc_ext/data/stock.html");
			channel3.put("layout", "T");
			channel3.put("name", "GMCCStockPrice");
			channel3.put("catalogId", "59f322bf-69f6-4660-9e23-8ea9dd0780bd");
			channel3.put("type", "1");
			ArrayList<Map> ary1 = new ArrayList();
			ary1.add(channel);
			ary1.add(channel1);
			ary1.add(channel2);
			ary1.add(channel3);
			model.put("channels", ary1);
			// Add other model data...

			request.setAttribute("model", model);
			// response.getOutputStream().println();
			chain.doFilter(request, response);
			// response.getWriter().toString();
		} catch (Throwable t) {
			// If an exception is thrown somewhere down the filter chain,
			// we still want to execute our after processing, and then
			// rethrow the problem after that.
			problem = t;
			t.printStackTrace();
		}

		// If there was a problem, we want to rethrow it if it is
		// a known type, otherwise log it.
		if (problem != null) {
			if (problem instanceof ServletException)
				throw (ServletException) problem;
			if (problem instanceof IOException)
				throw (IOException) problem;
			sendProcessingError(problem, response);
		}
	}

	/**
	 * Return the filter configuration object for this filter.
	 */
	public FilterConfig getFilterConfig() {
		return (this.filterConfig);
	}

	/**
	 * Set the filter configuration object for this filter.
	 * 
	 * @param filterConfig
	 *            The filter configuration object
	 */
	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	/**
	 * Destroy method for this filter
	 */
	public void destroy() {
	}

	/**
	 * Init method for this filter
	 */
	public void init(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
		if (filterConfig != null) {
			if (debug) {
				log("TemplateFilter:Initializing filter");
			}
		}
	}

	/**
	 * Return a String representation of this object.
	 */
	@Override
	public String toString() {
		if (filterConfig == null)
			return ("TemplateFilter()");
		StringBuffer sb = new StringBuffer("TemplateFilter(");
		sb.append(filterConfig);
		sb.append(")");
		return (sb.toString());
	}

	private void sendProcessingError(Throwable t, ServletResponse response) {
		String stackTrace = getStackTrace(t);

		if (stackTrace != null && !stackTrace.equals("")) {
			try {
				response.setContentType("text/html");
				PrintStream ps = new PrintStream(response.getOutputStream());
				PrintWriter pw = new PrintWriter(ps);
				pw
						.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); // NOI18N

				// PENDING! Localize this for next official release
				pw
						.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
				pw.print(stackTrace);
				pw.print("</pre></body>\n</html>"); // NOI18N
				pw.close();
				ps.close();
				response.getOutputStream().close();
			} catch (Exception ex) {
			}
		} else {
			try {
				PrintStream ps = new PrintStream(response.getOutputStream());
				t.printStackTrace(ps);
				ps.close();
				response.getOutputStream().close();
			} catch (Exception ex) {
			}
		}
	}

	public static String getStackTrace(Throwable t) {
		String stackTrace = null;
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			t.printStackTrace(pw);
			pw.close();
			sw.close();
			stackTrace = sw.getBuffer().toString();
		} catch (Exception ex) {
		}
		return stackTrace;
	}

	public void log(String msg) {
		filterConfig.getServletContext().log(msg);
	}

}
